package cn.edu.lingnan.tourism.controller;

import cn.edu.lingnan.tourism.exeption.TourismException;
import cn.edu.lingnan.tourism.pojo.User;
import cn.edu.lingnan.tourism.service.UserService;
import cn.edu.lingnan.tourism.utils.Md5Util;
import cn.edu.lingnan.tourism.utils.Result;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;
import java.util.Random;


@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private JavaMailSender javaMailSender;

    //用户注册
    @RequestMapping("/insertUser")
    public String insertUser(@RequestBody User user){
        try {
            user.setStatus("0");
            user.setPassword(Md5Util.encodeByMd5(user.getPassword()));
            int i = userService.insertUser(user);
            if(i==1){
                return new Result<>().success("注册成功");
            }else{
                return new Result<>().success("注册失败");
            }
        }catch (Exception e){
            return new Result<>().error("注册失败");
        }
    }

    //用户登录
    @RequestMapping("/login")
    public String selectUserByUsernameAndPassword(@RequestBody User loginuser,HttpSession session){
        try{
            loginuser.setPassword(Md5Util.encodeByMd5(loginuser.getPassword()));
            User user = userService.selectUserByUsernameAndPassword(loginuser);
            if(user.getCode()==null){
                return new Result<>().error("邮箱未激活");
            }
            session.setAttribute("user",user);
            return new Result<>().success(user);
        }catch (Exception e){
            return new Result<>().error(e.getMessage());
        }
    }

    //用户信息修改
    @PostMapping("/updateUser")
    public String updateUser(@RequestBody User user){
        try{
            userService.updateUser(user);
            User userByUid = userService.getUserByUid(user.getUid());
            return new Result<>().success(userByUid);
        }catch (TourismException e){
            return new Result<>().error(e.getMessage());
        }
    }
    //用户注销
    @RequestMapping("/destory")
    public String OutLogin (HttpSession session){
        int flag;
        session.removeAttribute("user");
        session.invalidate();
        return new Result<>().success("退出成功");
    }
    @RequestMapping("/editPassword")
    public String EditPassword(HttpSession session,@RequestBody User user){
    try{
        String code = (String) session.getAttribute("email");
        if(!code.equals(user.getCode())){
            return new Result<String>().error("验证码不正确");
        }
        User user1 = (User) session.getAttribute("user");
        if(user1.getEmail().equals(user.getEmail())){
            user.setUid(user1.getUid());
            user.setPassword(Md5Util.encodeByMd5(user.getPassword()));
            int userResult = userService.updateUser(user);
            return new Result<>().success(userResult);
        }
        return new Result<>().error("邮箱错误");
    }catch (Exception e){
        return new Result<>().error("服务器内部问题");
    }
}
@RequestMapping("/sendEmail")
    public String SendEmail(HttpSession session,@RequestBody String email){
    JSONObject parse = (JSONObject) JSON.parse(email);
    String searchStr = (String) parse.get("email");
    String trim = searchStr.trim();
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom("1178066084@qq.com");
    message.setTo(trim);//设置接收用户的邮箱
    message.setSubject("注册或重置密码");
    // 生成 6 位数字验证码
    String randomNumber = String.valueOf(new Random().nextInt(900000) + 100000);
    message.setText("你的邮箱验证码为 " + randomNumber);
    // 发送邮件
    javaMailSender.send(message);
    User user = new User();
    user.setEmail(trim);
    List<User> userByType = userService.getUserByType(user);
    if(userByType.size()==1){
        session.setAttribute("email",randomNumber);
        return new Result<>().success("发送成功");
    }else if(userByType.size()>1){
        return new Result<>().error("邮箱已存在");
    }else{
        return new Result<>().error("邮箱未注册");
    }
}
@RequestMapping("/activeEmail")
    public String ActiveEmail(HttpSession session,@RequestBody User user){
        User user1 = new User();
        user1.setEmail(user.getEmail());
        List<User> userByType = userService.getUserByType(user1);
        if(userByType.size()==0){
            return new Result<>().error("系统无该邮箱记录");
        }
        String code = (String) session.getAttribute("email");
        if(!user.getCode().equals(code)){
            return new Result<>().error("激活码不正确");
        }
        user.setUid(userByType.get(0).getUid());
        try{

            int i = userService.updateUser(user);
            if(i==1){
                return new Result<>().success("激活成功");
            }else{
                return new Result<>().error("激活失败");
            }
        }catch (TourismException e){
            return new Result<>().error("激活失败");
        }
    }

    //重置密码
    @RequestMapping("/rePwd")
    public String rePwd(@RequestBody User user,HttpSession session) throws Exception {
        String code = (String) session.getAttribute("email");
        if(!user.getCode().equals(code)){
            return new Result<>().error("邮箱验证码错误");
        }
        user.setCode(null);
        List<User> userByType = userService.getUserByType(user);
        User user1 = userByType.get(0);
        user1.setPassword(Md5Util.encodeByMd5("1234"));
        int i = userService.updateUser(user1);
        if(i==0){
            return new Result<>().error("重置失败");
        }
        return new Result<>().success("重置成功，密码为1234");
    }
}
